/**
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.google.wave.splash.auth;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.wave.splash.PortableRequestScope;
import com.google.wave.splash.RequestScopeExecutor;

import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Session-based request scope executor.
 *
 * @author (David Byttow)
 */
@Singleton
public class PortableRequestScopeExecutor implements RequestScopeExecutor {
  private final static Logger LOG = Logger.getLogger(PortableRequestScopeExecutor.class.getName());

  private final ExecutorService executor;
  private final PortableRequestScope requestScope;
  private final Provider<SessionContext> sessionProvider;

  @Inject
  PortableRequestScopeExecutor(ExecutorService executor, PortableRequestScope requestScope,
      Provider<SessionContext> sessionProvider) {
    this.executor = executor;
    this.requestScope = requestScope;
    this.sessionProvider = sessionProvider;
  }

  public void submit(final Runnable runnable) {
    final SessionContext session = sessionProvider.get();

    executor.submit(new Runnable() {
      @Override
      public void run() {
        requestScope.enter();
        requestScope.seed(SessionContext.class, session);

        try {
          runnable.run();
        } catch (Exception e) {
          LOG.log(Level.WARNING, "Error executing with portable scope.", e);
        } finally {
          requestScope.exit();
        }
      }
    });
  }
}
